Unbox as l-value in C#
What was rationale of having unboxed values in C# as r-values?
I've found for myself only two possible answer:
- predict and prevent long term managed pointers to the heap
- some primitive mechanism of unchangable value
But as for first - managed pointer to the heap appear in many other
forms in the code (for instance as this pointer of structure that is a
part of object in the heap), and as for second - I can change boxed value
using reflection mechanisms.
Rationale
Ref types in heap are always considered as l-values. And in my opinion
it would be reasonable to consider value types in heap as l-values as
well. I don't mean that this is so ubiquitous operation (unboxing to
l-value), but anyway in that cases where unboxing is used it could be
valuable, for instance in collections (in their present implementation) of
value types.
Implementation
Not big number of changes are required:
- FUNCBREC::bindExplicitConversion - the part about unboxing (mark
result as lvalue)
- ILGENREC::genAddress - generates address for unboxing cast
expression
- ILGENREC::genMemoryAddress - generates address for unboxing cast
expression
- ILGENREC::genFromAddress - generates store instruction for reference
of cast expression
That's all.
Example
Now I can compile and run following example:
public struct Rect
{
public int left
;public int top
;public int width
;public int height
;public override string
ToString
(){
return "left: " + left + ", top: " + top + ",
width: " + width +
", height: " +
height;
}public void Inflate
(int x
, int y
){
left -= x;
top -= y;
width += x * 2;
height += y * 2;
} }public class unbox
{
public static void Main
(string[] args
){
Rect r = new Rect();
object o = r;
Console.WriteLine(o);
r.Inflate(1, 1);
(Rect)o =
r;
Console.WriteLine(o);
((Rect)o).left ++;
r = (Rect)o;
Console.WriteLine(r);
((Rect)o).Inflate(-2,
-2);
Console.WriteLine(o);
} }
Questions and doubts
Looking from the more general perspective I do not see any need in box
and unbox il instructions, cast instructions could handle this work well.
What their rationale?
Share your thoughts with as about this problem.
Copyright (c) 2003-2005 by Nesterovsky bros